import 'package:amap_base/amap_base.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:hbtrans_flutter/beans/carenroll_bean.dart';
import 'package:hbtrans_flutter/beans/city_bean.dart';
import 'package:hbtrans_flutter/beans/country_bean.dart';
import 'package:hbtrans_flutter/utils/fluro.dart';
import 'package:hbtrans_flutter/utils/mydio.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../apis.dart';
import '../const.dart';
import '../routes.dart';

class CarEnroll extends StatefulWidget {
  @override
  _CarEnrollState createState() => _CarEnrollState();
}

class _CarEnrollState extends State<CarEnroll> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  var loadingDialog;
  List<CarenrollBean> schools = List();
  var cities = [
    CityBean(code: "130100", name: "石家庄市"),
    CityBean(code: "130200", name: "唐山市"),
    CityBean(code: "130300", name: "秦皇岛市"),
    CityBean(code: "130400", name: "邯郸市"),
    CityBean(code: "130500", name: "邢台市"),
    CityBean(code: "130600", name: "保定市"),
    CityBean(code: "130700", name: "张家口市"),
    CityBean(code: "130800", name: "承德市"),
    CityBean(code: "130900", name: "沧州市"),
    CityBean(code: "131000", name: "廊坊市"),
    CityBean(code: "131100", name: "衡水市")
  ];

  List<CountryBean> countries = List();
  final _amapLocation = AMapLocation();
  ReGeocodeResult reGeocodeResult;
  var lng;
  var lat;
  var _city = '';
  var _cityCode = '';
  var countiesMap;
  var _district = '';
  var _districtCode = '';
  var pickerCity;
  var pickerCountry;
  TextEditingController _controllerName =
      TextEditingController.fromValue(TextEditingValue(text: ''));
  var options = LocationClientOptions(
      isOnceLocation: false,
      locatingWithReGeocode: false,
      isWifiScan: true,
      isSensorEnable: true);

  //初始化定位监听
  _initLocation() async {
    print('_initLocation');
    PermissionStatus permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.location);
//    if(permission==PermissionStatus.granted){
    if(await Permissions().requestPermission()){
      print('startLocate');
      _amapLocation.startLocate(options).listen((_) => setState(() {
        lat = _.latitude;
        lng = _.longitude;
        _amapLocation.stopLocate();
        print('stopLocate');
        String _result =
            '坐标：${_.longitude}，${_.latitude} @ ${DateTime.now().hour}:${DateTime.now().minute}:${DateTime.now().second}';
        print(_result);
        _getAddress();

      }));
    }else{
      print('没有权限');
    }
  }

  Future _getAddress() async {
    AMapSearch()
        .searchReGeocode(LatLng(lat, lng), 100, 0)
        .then((reGeocodeResult) {
      setState(() {
        print(reGeocodeResult);
        _city = reGeocodeResult.regeocodeAddress.city;
        _district = reGeocodeResult.regeocodeAddress.district;
        _districtCode = reGeocodeResult.regeocodeAddress.adCode;
        _cityCode = '${_districtCode.substring(0, _districtCode.length - 1)}0';
        print('_cityCode$_cityCode,_districtCode$_districtCode');
        _getSchools();
      });
    });
  }

  _setPickerCities() {
    List<PickerItem<dynamic>> pickerItems = List();
    for (CityBean bean in cities) {
      pickerItems.add(PickerItem(
          value: Icons.add,
          text: Text(bean.name,
              style: TextStyle(color: const Color(0xff333333), fontSize: 16))));
    }
    return pickerItems;
  }

  _setPickerCountries() {
    List<PickerItem<dynamic>> pickerItems = List();
    for (CountryBean bean in countries) {
      pickerItems.add(PickerItem(
          value: Icons.add,
          text: Text(bean.name,
              style: TextStyle(color: const Color(0xff333333), fontSize: 16))));
    }
    return pickerItems;
  }

  _buildPickerCity() {
    pickerCity = Picker(
      adapter: PickerDataAdapter(data: _setPickerCities()),
      title: Text('请选择'),
      cancelText: '取消',
      confirmText: '确定',
      selectedTextStyle: TextStyle(color: Colors.blue),
      onConfirm: (Picker picker, List value) {
        setState(() {
          _city = cities[value[0]].name;
          _cityCode = cities[value[0]].code;
          _district = '选择区县';
          _districtCode = '';
        });
      },
    );
  }

  _buildPickerCountry() {
    countries.clear();
    for (var s in countiesMap[_cityCode]) {
      countries.add(CountryBean.fromJson(s));
    }
    Picker(
      adapter: PickerDataAdapter(data: _setPickerCountries()),
      title: Text('请选择'),
      cancelText: '取消',
      confirmText: '确定',
      selectedTextStyle: TextStyle(color: Colors.blue),
      onConfirm: (Picker picker, List value) {
        setState(() {
          _district = countries[value[0]].name;
          _districtCode = countries[value[0]].code;
          _getSchools();
        });
      },
    ).show(_scaffoldKey.currentState);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _amapLocation.init();
    _initLocation();
    _getCounties();
    _buildPickerCity();
  }

  @override
  void dispose() {
    _amapLocation.stopLocate();
    super.dispose();
  }

  _getCounties() async {
    MyDio.getInstance(url: Const.TRANS_SERVER_PATH).get(
      Apis.getCounties,
      (data) {
        print(data);
        if (loadingDialog != null) {
          loadingDialog = null;
          Navigator.pop(context);
        }
        setState(() {
          countiesMap = data;
        });
      },
    );
  }

  _getSchools() async {
    Map data = Map<String, dynamic>();
    data["district"] = _districtCode;
    MyDio.getInstance(url: Const.TRANS_SERVER_PATH).get(Apis.getSchools,
        (data) {
      print(data);
      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
      schools.clear();
      for (var s in data) {
        schools.add(CarenrollBean.fromJson(s));
      }
      setState(() {});
    }, params: data);
  }

  List<Widget> doWidgets() {
    List<Widget> listTitles = List();
    for (CarenrollBean bean in schools) {
      listTitles.add(buildListItem(context, bean));
    }
    return listTitles;
  }

  _toSign(CarenrollBean bean) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString("inscode", bean.inscode);
    preferences.setString("busiscope", bean.busiscope);
    print('inscode:${bean.inscode}');
    String route =
        '${Routes.sign}?name=${FluroConvertUtils.fluroCnParamsEncode(bean.name)}&address=${FluroConvertUtils.fluroCnParamsEncode(bean.address)}&phone=${bean.phone}&inscode=${bean.inscode}';
    Routes.router.navigateTo(context, route,
        replace: false, transition: TransitionType.fadeIn);
  }

  Widget buildListItem(BuildContext context, CarenrollBean bean) {
    return GestureDetector(
        onTap: () {
          _toSign(bean);
        },
        child: Card(
          margin: const EdgeInsets.all(0),
          elevation: 0,
          color: Colors.white,
          child: Padding(
            padding: const EdgeInsets.all(15),
            child: Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            ImageIcon(
                              AssetImage('images/icon_school.png'),
                              color: Color(0xff23AFDC),
                            ),
                            SizedBox(
                              width: 5,
                            ),
                            Text(bean.shortname,
                                style: TextStyle(
                                    color: Color(0xff333333), fontSize: 14))
                          ],
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            ImageIcon(
                              AssetImage('images/icon_dizhi.png'),
                              color: Color(0xff23AFDC),
                            ),
                            SizedBox(
                              width: 5,
                            ),
                            SizedBox(
                              width: 270,
                              child: Text(bean.address,
                                  style: TextStyle(
                                      color: Color(0xff666666), fontSize: 12)),
                            )
                          ],
                        ),
                      ],
                    ),
                    Text(bean.busistatus == '1' ? '营业' : '非营业',
                        style:
                            TextStyle(color: Color(0xff23AFDC), fontSize: 12)),
                  ],
                ),
              ],
            ),
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: const Text('学车报名'),
        backgroundColor: Color(0xff23AFDC),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          Container(
            color: Colors.white,
            height: 40,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
              child: Row(
                children: <Widget>[
                  SizedBox(width: 14),
                  GestureDetector(
                    onTap: () {
                      pickerCity.show(_scaffoldKey.currentState);
                    },
                    child: SizedBox(
                      width: 45,
                      height: 20,
                      child: Text(
                        _city,
                        style: TextStyle(
                            fontSize: 14, color: const Color(0xff333333)),
                      ),
                    ),
                  ),
                  SizedBox(width: 2),
                  Image.asset(
                    'images/ic_down_arrow.png',
                    height: 14,
                    width: 14,
                  ),
                  SizedBox(width: 9),
                  GestureDetector(
                    onTap: () {
                      _buildPickerCountry();
                    },
                    child: SizedBox(
                      width: 65,
                      height: 20,
                      child: Text(
                        _district,
                        style: TextStyle(
                            fontSize: 14, color: const Color(0xff333333)),
                      ),
                    ),
                  ),
                  SizedBox(width: 2),
                  Image.asset(
                    'images/ic_down_arrow.png',
                    height: 14,
                    width: 14,
                  ),
                  SizedBox(width: 10),
                  Expanded(
                    child: TextFormField(
                      controller: _controllerName,
                      style: TextStyle(fontSize: 12, color: Colors.grey),
                      decoration: InputDecoration(
//                        icon: Icon(
//                          Icons.search,
//                          color: Color(0xff23AFDC),
//                        ),
                          contentPadding:
                              const EdgeInsets.fromLTRB(12, 2, 0, 2),
                          hintText: '请输入驾校名称',
                          hintStyle:
                              TextStyle(color: Color(0xff999999), fontSize: 12),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(12),
                              ),
                              borderSide: BorderSide(
                                color: Color(0xff999999),
                                width: 1,
                              )),
                          enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(12),
                              ),
                              borderSide: BorderSide(
                                color: Color(0xff999999),
                                width: 1,
                              ))),
                      autofocus: false,
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(
            height: 1,
          ),
          Expanded(
            child: ListView.separated(
//              controller: _controller,
              shrinkWrap: true,
              itemBuilder: (context, index) => doWidgets()[index],
              separatorBuilder: (context, index) => Divider(
                color: Color(0xffF0F0F0),
                height: 1,
              ),
              itemCount: doWidgets().length,
            ),
          ),
        ],
      ),
    );
  }
}
